﻿import serial
import math
import os
import serial.tools.list_ports
import re
from collections import Counter
import random
plist = list(serial.tools.list_ports.comports())

frontPort = 'com10'
backPort = 'com3'
filename = "data" + str(random.uniform(0,1))

def getData(serPort, text, isBack):
    ser=serial.Serial(serPort,115200,timeout=0.5)
    a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    b = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for i in range(20):
        s = str(ser.readline())
        s = s.split(',')
        d = s[0]
        p = s[1]
        d = d.replace("b'Distance=  ", '')
        p = p.replace("peak= ",'')
        p = p.replace("peak=",'')
        p = p.replace("Peak=",'')
        p = p.replace("\\n'",'')
        a[i] = int(d)-1
        b[i] = int(p)
    r = Counter(a).most_common(1)[0][0]
    peak = max(b)
    print(text)
    print(r,peak)
    ser.close()
    if bool(1-isBack):
        dataString = str(r) + '\t' + str(peak) + '\t'
    else:
        dataString = str(r) + '\t' + str(peak) +  '\r\n'
    return dataString

count=1
while True:
    temp = input('按回车测量\n')
    with open(filename,"a") as f:
        f.write(getData(frontPort, "fontSide:", False))
        f.write(getData(backPort, "backSide:", True))